package com.apimanage.common.exception;

import com.apimanage.common.entity.Result;
import com.apimanage.common.response.ResultCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

import java.util.HashMap;
import java.util.Map;

/**
 * 全局异常处理类
 * 统一处理系统中抛出的各种异常
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    
    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 处理自定义API异常
     */
    @ExceptionHandler(ApiException.class)
    public ResponseEntity<Result<?>> handleApiException(ApiException e) {
        // 使用手动添加的getter方法
        Integer errorCode = e.getCode();
        String errorMessage = e.getMessage();
        log.error("API异常: {}", errorMessage);
        Result<?> result = Result.error(errorCode, errorMessage);
        return new ResponseEntity<>(result, HttpStatus.valueOf(errorCode));
    }

    /**
     * 处理请求参数校验异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<Result<?>> handleValidationException(MethodArgumentNotValidException e) {
        log.error("参数校验异常: {}", e.getMessage(), e);
        
        // 提取字段错误信息
        Map<String, String> fieldErrors = new HashMap<>();
        for (FieldError error : e.getBindingResult().getFieldErrors()) {
            fieldErrors.put(error.getField(), error.getDefaultMessage());
        }
        
        Result<Map<String, String>> result = Result.error(ResultCode.FAIL, "参数校验失败");
        result.setData(fieldErrors);
        return new ResponseEntity<>(result, HttpStatus.BAD_REQUEST);
    }

    /**
     * 处理404异常
     */
    @ExceptionHandler(NoHandlerFoundException.class)
    public ResponseEntity<Result<?>> handleNoHandlerFoundException(NoHandlerFoundException e) {
        // 直接使用固定消息，不依赖getMessage()
        log.error("请求路径不存在");
        Result<?> result = Result.error(404, "请求路径不存在");
        return new ResponseEntity<>(result, HttpStatus.NOT_FOUND);
    }

    /**
     * 处理系统异常
     */
    @ExceptionHandler(Exception.class)
    public ResponseEntity<Result<?>> handleException(Exception e) {
        log.error("系统异常: {}", e.getMessage(), e);
        // 为了安全，不将系统异常的详细信息返回给客户端
        Result<?> result = Result.error(ResultCode.FAIL, "系统内部错误，请稍后重试");
        return new ResponseEntity<>(result, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}